package com.fang.dubbo.mock.spi.balance;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.cluster.loadbalance.RandomLoadBalance;

import com.fang.dubbo.mock.common.EnvEnum;
import com.fang.dubbo.mock.common.MyEnvironment;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 自定义负载均衡策略
 * @date 2022/1/3 1:56 下午
 **/
@Slf4j
@Activate
public class FangLoadBalance extends RandomLoadBalance {

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        if (MyEnvironment.envEnum == EnvEnum.DEV) {
            for (Invoker<T> invoker : invokers) {
                if (invoker.getUrl().getIp().equals(url.getParameter("register.ip"))) {
                    log.info("dev environment use current pc first");
                    return invoker;
                }
            }
        }
        return super.doSelect(invokers, url, invocation);
    }
}
